<template>
  <div class="audition171">
    <p>1. commonjs实现模块化模拟：</p>
    <v-md-preview :text="text1" />
    <p>实现原理：</p>
    <p>读取文件内容，创建一个匿名函数，返回匿名函数执行结果</p>
    <p>2. requirejs模块化：</p>
    <p>使用：</p>
    <v-md-preview :text="text2" />
    <p>方法模拟：</p>
    <v-md-preview :text="text3" />
    <p>原理：</p>
    <p>需要写入依赖和回调函数，require的时候也需要用到依赖和回调函数</p>
  </div>
</template>

<script>
const prefix = '``` js'
const suffix = '```'
export default {
  name: 'Audition171',
  data() {
    return {
      text1: `${prefix}
      let fs = require(fs)
      function req(moduleName){
        let content = fs.readFileSync(moduleName);
        let fn  = new Function("exports","module","require","__dirname","__filename",content+"\n return module.exports")
        let module = {
            exports:{}
        };
        return fn(module.exports,module,req,__dirname,__filename);
      }
      \n${suffix}`,
      text2: `${prefix}
      define('name',[],function(){
        return 'requirejs'
      })
      define('say',['name'].function(name){
        return 'my name is' + name
      })
      require(['say'],function(text){
        console.log(text)
      })
      \n${suffix}`,
      text3: `${prefix}
      let factories = {}
      function define(moduleName,dependencies,factory){
        factory.dependencies = dependencies;//记住对应的依赖关系
        factories[moduleName] = factory;
      }
      function require(mods,callback){
        let result =  mods.map(mod=>{
          let factory = factories[mod];
          let exports ;
          let dependencies = factory.dependencies;
          require(dependencies,function(...args){//递归处理依赖关系
            exports = factory.apply(null,args)
          })
          return exports;
        })
        callback.apply(null,result)
      }
      \n${suffix}`,
    }
  }
}
</script>

<style>

</style>